package com.example.demo.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.querydsl.QPageRequest;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.example.demo.framework.ResultData;
import com.example.demo.framework.base.BaseController;
import com.example.demo.framework.util.AliPayConfig;
import com.example.demo.framework.util.DoubleUtil;
import com.example.demo.framework.util.JodaUtil;
import com.example.demo.model.Fund;
import com.example.demo.model.UserInfo;
import com.example.demo.repository.FundRepository;
import com.example.demo.repository.UserRepository;

/**
 * 资金记录
 * 
 * @author jc
 *
 */
@RestController
@RequestMapping("fund")
public class FundController extends BaseController {

	@Autowired
	FundRepository fundRepository;

	@Autowired
	UserRepository userRepository;

	/**
	 * 代理商-充值记录
	 * 
	 * @param pageNo
	 * @return
	 */
	@RequestMapping("findRecords")
	public Object findRecordsList(@RequestParam(value = "pageNo", defaultValue = "0") int pageNo, Fund fund) {
		Map<String, Object> data = new HashMap<>();
		fund.setuID(getUser().getUserID());
		Page<Fund> list = fundRepository.pageCriteria(fund, new QPageRequest(pageNo(pageNo), PAGESIZE));
		data.put("list", list);
		return new ResultData(data);
	}

	/**
	 * 代理商-充值
	 * 
	 * @param fund
	 * @return
	 */
	@Transactional
	@RequestMapping("addRecords")
	public Object addRecords(Fund fund) {
		Map<String, Object> data = new HashMap<>();
		UserInfo info = userRepository.getByUserID(getUser().getUserID());
		fund.setBeforeMoney(info.getUserMoney());
		fund.setCreateTime(JodaUtil.now());
		fund.setuID(getUser().getUserID());
		fund.setType(0);
		fund.setStatus(0);
		fundRepository.save(fund);
		data.put("fund", fund);
		return new ResultData(data);
	}

	/**
	 * 管理员-处理代理商充值
	 * 
	 * @param fund
	 * @return
	 */
	@Transactional
	@RequestMapping("addAgentRecords")
	public Object addAgentRecords(Fund fund) {
		Map<String, Object> data = new HashMap<>();
		Fund fund2 = fundRepository.getOne(fund.getfID());
		UserInfo info = userRepository.getOne(fund2.getuID());
		if (fund.getStatus() == 2) {
			fund2.setStatus(2);
			fund2.setWithNote(fund.getWithNote());
			fund2.setUpdateTime(JodaUtil.now());
			fundRepository.save(fund2);

			info.setUserMoney(DoubleUtil.add(info.getUserMoney(), fund2.getBeforeMoney()));
			userRepository.save(info);
		} else {
			fund2.setStatus(3);
			fund2.setWithNote(fund.getWithNote());
			fund2.setUpdateTime(JodaUtil.now());
			fundRepository.save(fund2);
		}
		data.put("info", info);
		return new ResultData(data);
	}

	/**
	 * 账户充值
	 * 
	 * @return
	 */
	@Transactional
	@RequestMapping("accountInpour")
	public Object accountInpour(double amount) {
		Map<String, Object> data = new HashMap<>();
		UserInfo user = getUser();
		AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
				AliPayConfig.APP_ID, AliPayConfig.APP_PRIVATE_KEY, "json", AliPayConfig.CHARSET,
				AliPayConfig.ALIPAY_PUBLIC_KEY, "RSA2"); // 获得初始化的AlipayClient
		AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();// 创建API对应的request类
		request.setNotifyUrl(AliPayConfig.NOTIFY_URL);// 回调地址
		JSONObject json = new JSONObject();
		json.put("out_trade_no", createOrderID());
		json.put("total_amount", amount + "");
		json.put("subject", "充值金额：" + amount);
		json.put("store_id", "ly_001");
		json.put("timeout_express", "90m");
		request.setBizContent(json.toJSONString());
		AlipayTradePrecreateResponse response;
		try {
			response = alipayClient.execute(request);
			log.info(response.getBody());
			String qr_code = JSON.parseObject(response.getBody()).getJSONObject("alipay_trade_precreate_response")
					.getString("qr_code");
			data.put("qr_code", qr_code);
		} catch (AlipayApiException e) {
			e.printStackTrace();
		}
		fundRepository.save(Fund.buildAccountInpour(json.getString("out_trade_no"), user.getUserID(), JodaUtil.now(),
				json.getDouble("total_amount"), user.getUserMoney(), user.getUserMoney()));
		return new ResultData(data);
	}

	private String createOrderID() {
		return JodaUtil.now(JodaUtil.DATETIME_FORMAT_03) + generateRandomNum6bit();
	}

}
